package crp.core.workflow.app.loaders;

import com.google.common.collect.Streams;
import com.qwlabs.lang.C2;
import com.qwlabs.security.Caller;
import crp.core.department.domain.models.DepartmentEntity;
import crp.core.faculty.domain.services.FacultySearcher;
import crp.core.security.Callers;
import crp.core.workflow.domain.models.WorkflowCandidate;
import crp.core.workflow.domain.models.WorkflowCandidateType;
import crp.core.workflow.domain.services.WorkflowCandidateLoader;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;

@ApplicationScoped
public class WorkflowCandidateDepartmentLoader implements WorkflowCandidateLoader {
    private final FacultySearcher facultySearcher;

    @Inject
    public WorkflowCandidateDepartmentLoader(FacultySearcher facultySearcher) {
        this.facultySearcher = facultySearcher;
    }

    @Override
    public Set<WorkflowCandidate> load(@NotNull Caller caller) {
        return C2.set(Streams.concat(loadFacultyDepartment(caller), loadStudentDepartment(caller)),
                department -> WorkflowCandidate.builder()
                        .type(WorkflowCandidateType.DEPARTMENT)
                        .target(department.getId())
                        .build());
    }

    private Stream<DepartmentEntity> loadFacultyDepartment(@NotNull Caller caller) {
        return Optional.ofNullable(Callers.facultyId(caller))
                .map(facultySearcher::findDepartments)
                .orElseGet(Stream::empty);
    }

    private Stream<DepartmentEntity> loadStudentDepartment(@NotNull Caller caller) {
        return Stream.empty();
    }
}
